package promote.brozen.netty.jav.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author Brozen
 * @date 2020/9/27 1:14 PM
 * @email brozen@qq.com
 */
public class AioServerAcceptor implements CompletionHandler<AsynchronousSocketChannel, AioServer> {

    @Override
    public void completed(AsynchronousSocketChannel sc, AioServer aioServer) {
        // 准备下一次连接
        aioServer.ssc.accept(aioServer, this);

        System.out.println("客户端连接！" + sc);

        // 读取数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        AioReader reader = new AioReader(sc, buffer);
        reader.setEcho(true);
        reader.setRole("Server");
        sc.read(buffer, reader, reader);
    }

    @Override
    public void failed(Throwable exc, AioServer attachment) {
        System.out.println("客户端连接失败！");
        exc.printStackTrace();
    }
}
